const knex = require('../db/knex');

class CartModel {
  static async getCartItemById(cartId) {
    return await knex('cart')
      .where({ cart_id: cartId })
      .first();
  }
  static async addToCart(userId, itemId, quantity, subtotal) {
    return await knex('cart').insert({
      user_id: userId,
      item_id: itemId,
      quantity,
      subtotal
    }).returning('*');
  }

  static async updateCart(cartId, quantity, subtotal) {
  const rowsUpdated = await knex('cart')
    .where({ cart_id: cartId })
    .update({ quantity, subtotal });

  if (rowsUpdated > 0) {
    return await this.getCartItemById(cartId); // 重新查询更新后的数据
  }
  return null;
}

static async removeFromCart(cartId) {
  const rowsDeleted = await knex('cart')
    .where({ cart_id: cartId })
    .del();
  return rowsDeleted; // 返回受影响行数
}

  static async getCartItems(userId) {
    return await knex('cart')
      .join('items', 'cart.item_id', '=', 'items.item_id')
      .select(
        'cart.cart_id',
        'items.item_id', // 确保返回 item_id
        'items.product_name',
        'items.product_price',
        'cart.quantity',
        'cart.subtotal'
      )
      .where({ 'cart.user_id': userId });
  }

  static async clearCart(userId) {
    return await knex('cart')
      .where({ user_id: userId })
      .del();
  }
}

module.exports = CartModel;